<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>post请求</title>
</head>
<body>
<h1>postAjax</h1>
<form action="" id="aForm">

  <input placeholder="请输入用户名" id="name" type="text" name="name">
  <input placeholder="请输入性别" id="sex" type="text" name="sex">
  <input placeholder="请输入年龄" id="age" type="text" name="age">
  <button id="btn">提交数据</button>

</form>
<script>
  const name = document.querySelector('#name')
  const sex = document.querySelector('#sex')
  const age = document.querySelector('#age')
  const btn = document.querySelector('#btn')
  const aForm = document.querySelector('#aForm')

  aForm.onsubmit = function () {

    const nameV = name.value
    const sexV = sex.value
    const ageV = age.value

    const xhr = new XMLHttpRequest()
    xhr.open('POST','/postData',true)
    //添加提交值的类型
    xhr.setRequestHeader('content-type','application/json;charset=utf-8')
    xhr.send(JSON.stringify({
      name:nameV,
      sex:sexV,
      age:ageV
    }))
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4&&xhr.status>=200&&xhr.status<=299){
        console.log(xhr.responseText)
      }
    }

    return false
  }

</script>
</body>
</html>